package com.easy.concert.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class DeepSeekService {
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";

    @Value("${deepseek.api-key}")
    private String apiKey;

    public String sendRequest(String prompt) throws IOException {
        // 验证API密钥是否存在
        if (apiKey == null || apiKey.trim().isEmpty()) {
            throw new IllegalArgumentException("DeepSeek API密钥未配置");
        }

        // 创建HTTP客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat"); // 确认模型名称正确

        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", prompt);
        messages.add(message);
        requestBody.put("messages", messages);

        // 创建POST请求
        HttpPost httpPost = new HttpPost(API_URL);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + apiKey);
        httpPost.setEntity(new StringEntity(requestBody.toString(), "UTF-8"));

        // 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            int statusCode = response.getStatusLine().getStatusCode();
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

            // 检查第三方API返回的状态码
            if (statusCode != 200) {
                throw new IOException("DeepSeek API请求失败: 状态码=" + statusCode + ", 响应=" + responseBody);
            }

            return responseBody;
        } catch (IOException e) {
            // 捕获并包装异常，添加更多上下文信息
            throw new IOException("调用DeepSeek API时发生错误: " + e.getMessage(), e);
        }
    }
}
